package com.weekdo.moviecomic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class SearchMovie extends Activity {
	private EditText searchKey;
	private Button searchButton;
	private ListView listView;

	private String WEB_HOST = "http://192.168.1.51";
	private String WEB_GET_LIST_URL = WEB_HOST+"/comic/get_comic_list.php";
	private ArrayList<ArrayList<String>> searchResult;
	private WebSimpleAdapter searchResultAdapter;


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);

		listView = (ListView) findViewById(R.id.SearchResult);
		listView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> view, View arg1, int id,
					long arg3) {
				String url = WEB_HOST+searchResult.get(id).get(3);
				String name = searchResult.get(id).get(0);
				Toast.makeText(view.getContext(), "Downloading \""+name+"\"", 5000).show();
				

		        if (downloadFile(url))
				{
					Toast.makeText(view.getContext(), "Download complete!", 5000).show();
				} else {
					Toast.makeText(view.getContext(), "Download failed.", 5000).show();
				}
			}

		});


		searchKey = (EditText) findViewById(R.id.searchKey);
		searchButton = (Button) findViewById(R.id.searchButton);
		searchButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchResult = getSearchResult();
				
				ArrayList<HashMap<String, Object>> itemList
					= new ArrayList<HashMap<String, Object>>();
				
				Iterator<ArrayList<String>> iter = searchResult.iterator();
				while (iter.hasNext()) {
					ArrayList<String> info = iter.next();
					HashMap<String, Object> Item = new HashMap<String, Object>();
					Item.put("img", WEB_HOST+"/"+info.get(2));
					Item.put("name", info.get(0)+"\n"+info.get(1));
					itemList.add(Item);
				}

				searchResultAdapter = new WebSimpleAdapter(v.getContext(),
						itemList,
						R.layout.search_result_item,
						new String[] { "img", "name"},
						new int[] { R.id.img, R.id.name});
				listView.setAdapter(searchResultAdapter);
			}

		});

	}

	public ArrayList<ArrayList<String>> getSearchResult() {

		String webResult = "";

		ArrayList<ArrayList<String>> resultList = new ArrayList<ArrayList<String>>();

		try {
			URL url = new URL(WEB_GET_LIST_URL);//+"?r="+Math.random());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(1000);
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("accept", "*\\/*");
			String location = conn.getRequestProperty("location");
			int resCode = conn.getResponseCode();
			conn.connect();
			
			InputStream inputStream = conn.getInputStream();
			BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
						
			char[] buffer = new char[102400];
			int bufferLength;
			while ((bufferLength = bufferReader.read(buffer)) > 0)
			{
				webResult += new String(buffer, 0, bufferLength);
			}
			
			webResult = webResult.trim();
			
			conn.disconnect();
			inputStream.close();
			//Toast.makeText(this, str, 5000).show();

		} catch (Exception ee) {
			System.out.print("ee:" + ee.getMessage());
		}


		for (String line : webResult.split("\n"))
		{
			line = line.trim();
			if (line.length() == 0) continue;

			ArrayList<String> tempArrayList = new ArrayList<String>();
			for (String item : line.split("\\|"))
			{
				tempArrayList.add(item);
			}
			//Log.d("  LINE --- ", line);
			//Log.d("ITEM INFO --- ", tempArrayList.toString());

			resultList.add(tempArrayList);
		}
		return resultList;
	}
	
	public boolean downloadFile(String fileUrl)
	{
		try {
			URL url = new URL(fileUrl);
			String localFilename = "";
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			
			localFilename = fileUrl.substring(fileUrl.lastIndexOf("/")+1);

			File localFile = new File(FileManager.MCK_ARCHIVE_DIR, localFilename);
			FileOutputStream fos = new FileOutputStream(localFile);
			
			  
			byte[] bt = new byte[1024];	
			int i = 0;

			while ( (i = is.read(bt)) > 0 )  
			{
				fos.write(bt, 0, i);
			}

			//Log.d("___________________", "It goes here...");

			fos.close();
			is.close();
			return true;
		} catch (Exception ee) {
			System.out.print("ee:" + ee.getMessage());
			return false;
		}
	}
}